package file_functions;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Download extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	private static final int BUFSIZE = 4096;
       
    public Download() 
    {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		File file = new File(new String(request.getParameter("file").getBytes("ISO-8859-1"), "UTF8"));
        int length;
        ServletOutputStream outStream = response.getOutputStream();
        ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(file.getName());
        
        //sets response content type
        if (mimetype == null)
            mimetype = "application/octet-stream";
        
        response.setContentType(mimetype);
        response.setContentLength((int)file.length());
        String fileName = file.getName();
        
        //sets HTTP header
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        
        byte[] byteBuffer = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        
        //reads the file's bytes and writes them to the response stream
        while ((in != null) && ((length = in.read(byteBuffer)) != -1))
        	outStream.write(byteBuffer, 0, length);
        
        in.close();
        outStream.close();
	}

}
